package com.runvp.netty.runnables;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.enums.NettyCmd;
import com.runvp.common.enums.NettyType;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.netty.constant.NettyConstant;
import com.runvp.service.tcp.TcpService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DeviceReqStopChargRunnable implements Runnable {

    private Channel channel;

    private TcpService tcpService;

    private MessageReceiveBody parseBody;

    public DeviceReqStopChargRunnable(Channel channel, TcpService tcpService, MessageReceiveBody parseBody) {
        this.channel = channel;
        this.tcpService = tcpService;
        this.parseBody = parseBody;
    }

    @Override
    public void run() {
//        handle(channel);
    }


    /**
     * 设备回应启动充电
     */
    public JSONObject handle(Channel channel) {
        long st = System.currentTimeMillis();
        long ast = st;
        String sn = "";
        try{
            String batchNo = System.nanoTime()+"";
            String json = JSONObject.toJSONString(parseBody);
            log.info("设备回应充电结束报文实体 ：{}", json);
            sn = NettyConstant.allOnlineChannleIds.get(NettyConstant.getChannelId(channel));
            JSONObject body = parseBody.getBodyJson();
            return body;
        }catch (Exception e){
            log.error("本次设备回应充电结束【{}】处理异常共耗时:【{} ms】,error:{}",sn ,(System.currentTimeMillis()-ast),e.getMessage());
        }finally {
            log.info("本次设备回应充电结束【{}】线程池内解析处理共耗时:【{} ms】",sn,(System.currentTimeMillis()-ast));
        }
        return new JSONObject();
    }

    /**
     * 默认报文
     *
     * @return MessageResBody
     */
    public MessageResBody defaultRes() {
        JSONObject body = handle(channel);
        String oid = body.getString( "oid");
        return buildRes(oid);
    }
    /**
     * 默认报文
     *
     * @return MessageResBody
     */
    public MessageResBody buildRes(String id) {
        MessageResBody resBody = new MessageResBody(NettyType.SERVER_RECEIVE_DEVICE.getCode(), NettyCmd.SERVER_RES_CHARG_END_REPORT.getCode());
        resBody.setDid("000000000000");
        resBody.setVersion("01");
        resBody.setBodyJson(buildBody(id)).buildRes();
        return resBody;
    }

    /**
     * 结构结果体
     * @return str
     */
    private JSONObject buildBody(String id){
        JSONObject map = new JSONObject();
        map.put("oid",id);
        return map;
    }

}
